import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select

from lib.cfg import *


class SMP_UI:

    def __init__(self):
        options = webdriver.ChromeOptions()
        options.add_experimental_option(
            'excludeSwitches', ['enable-logging'])
        self.wd = webdriver.Chrome(options=options)
        self.wd.implicitly_wait(10)

    def login(self, username, password):
        self.wd.get(SMP_URL_LOGIN)
        if username is not None:
            self.wd.find_element(By.CSS_SELECTOR, '#username').send_keys(username)
        if password is not None:
            self.wd.find_element(By.CSS_SELECTOR, '#password').send_keys(password)
        self.wd.find_element(By.CSS_SELECTOR, '#loginBtn').click()

    def add_device(self, kind, model, desc):
        toBtn = self.wd.find_element(By.CSS_SELECTOR, '.btn')
        if toBtn.text == '添加':
            toBtn.click()
        Select(smpUI.wd.find_element(By.CSS_SELECTOR, '#device-type')).select_by_visible_text(kind)

        ele = self.wd.find_element(By.CSS_SELECTOR, '#device-model')
        ele.clear()
        ele.send_keys(model)

        ele = self.wd.find_element(By.CSS_SELECTOR, '#device-model-desc')
        ele.clear()
        ele.send_keys(desc)

        self.wd.find_element(By.CSS_SELECTOR, '.add-one-submit-btn-div .btn').click()

    def get_key_msg(self):
        try:
            values = smpUI.wd.find_elements(By.CSS_SELECTOR, '.field-value')[:3]
            deviceModels = [value.text for value in values]
        except:
            deviceModels = []
        return deviceModels

    def del_first_item(self) -> bool:
        eles = self.wd.find_elements(By.CSS_SELECTOR, '.result-list-item-btn-bar>.btn-no-border')
        if not eles:
            return False
        eles[0].click()
        self.wd.switch_to.alert.accept()

    def add_svc_rule(self, ruleName: str, ruleType: str,
                     minFee: str, estFee: str,
                     feeRate=None, ruledesc=None):
        """
                添加业务规则
                :param ruleName: 规则名称
                :param ruleType: 规则类型，只能是：后付费-上报业务量、预付费-下发费用、预付费-下发业务量
                :param minFee: 最小费用，不需要时，填写空字符串
                :param estFee: 预计费用，不需要时，填写空字符串
                :param ruledesc: 描述
                :param feeRate: 费率， 如果ruleType是
                   预付费-下发费用： 不用填写
                   预付费-下发业务量： 格式为 ['千瓦时', '1']， 元素分别是 单位、单价
                   后付费-上报业务量： 格式为 [
                        ['10L', '小时','1'],
                        ['20L', '小时','2'],
                    ]， 每个元素里面分别是 ： 业务码、单位、单价
                :return:
                """
        toBtn = self.wd.find_element(By.CSS_SELECTOR, '.btn')
        if toBtn.text == '添加':
            toBtn.click()
        ele = self.wd.find_elements(By.CSS_SELECTOR, '.add-one-form input')[0]
        ele.clear()
        ele.send_keys(ruleName)

        Select(self.wd.find_element(By.CSS_SELECTOR, '#rule_type_id')).select_by_visible_text(ruleType)
        if ruleType != '后付费-上报业务量':
            if minFee:
                ele = self.wd.find_elements(By.CSS_SELECTOR, '[type="number"]')[0]
                ele.clear()
                ele.send_keys(minFee)
            if estFee:
                ele = self.wd.find_elements(By.CSS_SELECTOR, '[type="number"]')[1]
                ele.clear()
                ele.send_keys(estFee)

        if ruledesc:
            ele = self.wd.find_element(By.XPATH,
                                       '//div[@class="add-one-form"]/div[@class="field"][last()]//input[last()]')
            ele.clear()
            ele.send_keys(estFee)
        if ruleType == '预付费-下发费用':
            pass
        elif ruleType == '后付费-上报业务量':
            while True:
                eles = self.wd.find_elements(By.CSS_SELECTOR, '.fee-rate-list span:nth-last-child(1)')
                if eles:
                    eles[0].click()
                else:
                    break
            for one in feeRate:
                self.wd.find_element(By.CSS_SELECTOR, '.fee-rate-list button').click()
                eles = self.wd.find_element(By.CSS_SELECTOR, '.fee-rate-list div:nth-last-of-type(2)')
                eles.find_element(By.CSS_SELECTOR, 'input:nth-last-of-type(3)').send_keys(one[0])
                eles.find_element(By.CSS_SELECTOR, 'input:nth-last-of-type(2)').send_keys(one[1])
                eles.find_element(By.CSS_SELECTOR, 'input:nth-last-of-type(1)').send_keys(one[2])
        elif ruleType == '预付费-下发业务量':
            eles = self.wd.find_elements(By.CSS_SELECTOR, '.fee-rate-list input')
            eles[0].send_keys(feeRate[0])
            eles[1].send_keys(feeRate[1])
        else:
            raise Exception('ruleType 参数错误')

        self.wd.find_element(By.CSS_SELECTOR, '.add-one-submit-btn-div .btn').click()

    def get_first_svc_rule(self):
        Spans = self.wd.find_elements(By.XPATH, '//div[@class="result-list-item-info"]/div/span[@class="field-value"]')
        services = [span.text for span in Spans[:2]]

        spans = Spans[2].find_elements(By.CSS_SELECTOR, 'span')
        for span in spans:
            services.append(span.text)
        services.append(Spans[3].text)
        return services

    def add_device_true(self, device_type, device_model, rule_id, device_item, device_desc):
        toBtn = self.wd.find_element(By.CSS_SELECTOR, '.btn')
        if toBtn.text == '添加':
            toBtn.click()
        Select(self.wd.find_element(By.CSS_SELECTOR, '#device-type')).select_by_visible_text(device_type)
        Select(self.wd.find_element(By.CSS_SELECTOR, '#device-model')).select_by_visible_text(device_model)
        Select(self.wd.find_element(By.CSS_SELECTOR, '#svc-rule-id')).select_by_visible_text(rule_id)

        ele = self.wd.find_element(By.CSS_SELECTOR, '#device-sn')
        ele.clear()
        ele.send_keys(device_item)

        ele = self.wd.find_element(By.CSS_SELECTOR, '#device-desc')
        ele.clear()
        ele.send_keys(device_desc)

        self.wd.find_element(By.CSS_SELECTOR, '.add-one-submit-btn-div span').click()

    def get_first_device_true(self):
        values = self.wd.find_elements(By.CSS_SELECTOR, '.result-list-item-info .field-value')[:6]
        device_trues = [value.text for value in values]
        device_trues[3] = '1'
        return device_trues


smpUI = SMP_UI()
